/*
 *  Copyright (c) 2018, Infineon Technologies AG
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification,are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holders nor the names of its contributors
 *  may be used to endorse or promote products derived from this software without
 *  specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  To improve the quality of the software, users are encouraged to share
 *  modifications, enhancements or bug fixes with Infineon Technologies AG
 *  dave@infineon.com).
 */
/**
 * \defgroup communication Communication
 * @{
 */
/**
 * \file    communication.h
 * \author  Manuel Escudero Rodriguez
 * \date    08.05.2018
 * \brief   Communication code
 */
#ifndef __COMMUNICATION_H_
#define __COMMUNICATION_H_

#include "controller.h"
#include "xmc_flash.h"
extern uint16_t ADC_VO_RESULT_power_test;
extern uint16_t reference_power_test;
extern uint32_t time_count_while;
extern uint32_t time_count_power;
extern int32_t voltage_error_voltage_ctr;
extern uint16_t reference_new_test;
extern uint32_t adc_io_measure_power_test;
extern uint16_t reference_startup_power_test;
extern uint8_t  adc_ovp_error_PN_flag;
extern int32_t adc_ovp_error_test;
extern uint16_t ADC_IL_RESULT_test;
extern uint16_t ADC_IO_RESULT_test;
extern uint16_t ADC_IL_RESULT_max_test;
extern uint16_t ADC_IO_RESULT_max_test;
extern uint8_t ADC_IO_RESULT_PN_test;
// extern uint16_t TRAPPING_flag;
extern uint16_t ovp_flag;
extern uint16_t uvp_flag;
// extern uint16_t ovp_off_flag;
extern uint16_t set_off_flag;
extern uint16_t VIN_FAIL_TRAPPING_flag;
// extern uint32_t voltage_error_test;
// extern uint16_t BOOST_VIN_NOISE_OVERSHOOT_test;
// extern uint16_t zhengfu_flag;//正
// extern uint16_t duty_out_test;
// extern uint16_t burst_in_cnt_TRAPPING_flag;
// extern uint16_t burst_pulse_cnt_TRAPPING_flag;
// extern uint16_t soft_TRAPPING_flag;
extern uint16_t reference_test;
extern uint16_t ADC_VIN_RESULT_test;
extern uint16_t phase_out_test;
// extern uint32_t adc_vout_measure_test;
// extern uint16_t STOP_flag;
extern uint16_t ADC_VO_RESULT_test;
// extern uint16_t ADC_VO_RESULT_STOP_test;
// extern uint16_t on_off_STOP;
// extern uint16_t on_off_no_START_EN;
// extern uint16_t ADC_VIN_RESULT_STOP_test;
// extern uint32_t duty_test;
// extern uint16_t duty_flag;
// extern uint32_t adc_io_zero_test;
// extern uint32_t adc_io_zero_test_before;
extern uint16_t cr_value_test;
extern uint16_t duty_init_test;
extern uint16_t duty_test;
extern uint16_t duty_test_max;
extern uint16_t boost_start_up_init_count;
extern uint16_t boost_start_up_init_HICCUP_count;
/**
 * \name Converter ID
 * @{
 */
/** Converter identification number. PSFB 3300W. [integer] */
#define CONVERTER		(1) 
/** Number of bits of subversion. [integer] */
#define VERSION_BITS	(8)
/** Main version number. [integer] */
#define VERSION			(1)
#if VERSION >= (1 << VERSION_BITS)
	#error "VERSION should be smaller than (2^VERSION_BITS)." 
#endif
/** Main version number. [integer] */
#define SUB_VERSION		(0)
#if SUB_VERSION >= (1 << VERSION_BITS)
	#error "SUB_VERSION should be smaller than (2^VERSION_BITS)." 
#endif
/** @} */

/** Message */
typedef union
{
    struct
    {
		uint8_t _fill[3];
        uint8_t command; /**< Protocol command */
        union
        {
            uint32_t ui32[1];
            uint16_t ui16[2];
            uint8_t ui8[4];
        } payload; /**< Message data */
    } msg;
    struct
    {
		uint8_t _fill[3];
        uint8_t ui8[5];
    } raw;
} msg_t;

/**
 * \name Serial communication commands
 * Communication blocks of 3 bytes. 1 byte command, 2 bytes payload.
 * |-------------|-------------|-------------|-------------|-------------|
 *     0x55				CMD			DATA_0		  DATA_1		 CRC
 * @{
 */
/** Can be combined with some commands for a write operation of a parameter. */
#define UART_WRITE_MSK      	(0x00)
/** Can be combined with some commands for a read operation of a parameter. */
#define UART_READ       		(0x80)

/** Output voltage setting */
#define UART_OUT_V       		(0x01)
/** Dead time A B setting */
#define UART_DT_A_B      		(0x02)
/** Dead time C D setting */
#define UART_DT_C_D      		(0x03)
/** Read status. Status word */
#define UART_STATUS_S       	(0x04)
/** Read status. Status word */
#define UART_STATUS_F     		(0x05)
/** Saves parameters into flash. This takes large time. */
#define UART_SAVE           	(0x06)
/** Restore parameters from flash. This is done during startup by default. */
#define UART_RESTORE        	(0x07)
/** Synchronous switch ON delay. */
#define UART_SYNC_ON_DLY		(0x08)
/** Synchronous switch OFF delay. */
#define UART_SYNC_OFF_DLY		(0x09)
/** Synchronous current dependency factor. */
#define UART_SYNC_ON_IL_F		(0x0A)
/** Synchronous current dependency ratio. */
#define UART_SYNC_ON_IL_R		(0x0B)
/** Synchronous current dependency factor. */
#define UART_SYNC_OFF_IL_F		(0x0C)
/** Synchronous current dependency ratio. */
#define UART_SYNC_OFF_IL_R		(0x0D)
/** Bridge current dependency factor. */
#define UART_BRIDGE_AB_IL_F		(0x0E)
/** Bridge current dependency ratio. */
#define UART_BRIDGE_IL_R		(0x0F)
/** Start enable command. */
#define UART_START_EN       	(0x10)
/** Synchronous normal mode threshold. */
#define UART_SYNC_DCM			(0x11)
/** Synchronous DCM mode threshold. */
#define UART_SYNC_ICP			(0x12)
/** Fan protection enabling. */
#define UART_DEBUG_FAN      	(0x13)
/** Vin protection enabling. */
#define UART_DEBUG_VIN      	(0x14)
/** Soft start protection enabling. */
#define UART_DEBUG_SOFT     	(0x15)
/** Maximum phase. */
#define UART_MAX_PHASE      	(0x16)
/** Minimum phase. */
#define UART_MIN_PHASE      	(0x17)
/** Burst phase. */
#define UART_BURST_PHASE     	(0x18)
/** Stop PWM limit. */
#define UART_BURST_STOP_LIMIT	(0x19)
/** Burst low threshold. */
#define UART_BURST_LOW_LIMIT	(0x1A)
/** Burst high threshold. */
#define UART_BURST_HIGH_LIMIT	(0x1B)
/** Burst skipping cycles. */
#define UART_BURST_TRAP_CYC		(0x1C)
/** Burst skipping cycles. */
#define UART_BURST_LENGHT		(0x1D)
/** Brown in voltage. */
#define UART_VIN_MIN_HIGH		(0x1E)
/** Bridge current dependency factor. */
#define UART_BRIDGE_CD_IL_F		(0x1F)
/** Synchronous switch ON delay. */
#define UART_SYNC_ON_DCM_DLY	(0x24)
/** Boost dead time A B setting */
#define BOOST_UART_DT_A_B		(0x31)
/** Boost dead time C D setting */
#define BOOST_UART_DT_C_D		(0x32)

/** Metering of output voltage. */
#define METER_VO				(0x20)
/** Metering of output current. */
#define METER_IO				(0x21)
/** Metering of input voltage. */
#define METER_VIN				(0x22)
/** Metering of input current. */
#define METER_IIN				(0x23)

/** Version of software. */
#define SOFT_VER				(0x25)
/** Converter identifier. */
#define CONVERTER_ID			(0x26)
/** NTC temperature. */
#define NTC_TMP					(0x27)
/** Die temperature. */
#define DIE_TMP					(0x28)

/** Buck-Boost mode operation. */
#define UART_BUCK_BOOST_SLCTN	(0x30)
/** @}*/

/**
 * \name Serial communication payloads
 * Communication blocks of 3 bytes. 1 byte command, 2 bytes payload.
 * |-------------|-------------|-------------|-------------|-------------|
 *     0x55				CMD			DATA_0		  DATA_1		 CRC
 * @{
 */
/** ON-OFF command. Start payload */
#define UART_ON_OFF_START		(0x8080)
/** ON_OFF command. Stop payload */
#define UART_ON_OFF_STOP    	(0x0101)
/** Buck-Boost mode selection. Boost mode payload. */
#define UART_BOOST_MODE	    	(0x8080)
/** Buck-Boost mode selection. Buck mode payload. */
#define UART_BUCK_MODE	    	(0x0101)
/** @}*/

/** Master key used for the storage of some default parameters first upload of the software. */
#define MASTER_KEY				(1)
/** Clock divider for message transmission frequency. */
#define UART_TRANSMIT_CLK_DIV	(2)

/*
 * Warning: for uC with the software already running.
 * If the order of these parameters is altered the values previously stored in
 * flash would not be in place. Adjust the parameters again through the GUI.
 */
/** Converter parameters */
typedef struct
{
    uint16_t voltage_reference; /**< Voltage reference of the converter. [ADC_units] */
    uint16_t dead_time_A_B; /**< Dead time for bridge signals A B. [CCU_clock] */
    uint16_t dead_time_C_D; /**< Dead time for bridge signals C D. [CCU_clock] */
    uint16_t synch_ON_dly; /**< Delay before rising edge of synchronous rectifiers. [CCU_clock] */
    uint16_t synch_OFF_dly; /**< Delay before falling edge of synchronous rectifiers. [CCU_clock] */
    uint16_t synch_ON_il_ratio; /**< Ratio of the ON dependency with the current. [Power of 2] */
    uint16_t synch_OFF_il_ratio; /**< Ratio of the OFF dependency with the current. [Power of 2] */
    uint16_t synch_ON_il_factor; /**< Factor of the ON dependency with the current. [integer] */
    uint16_t synch_OFF_il_factor; /**< Factor of the OFF dependency with the current. [integer] */
    uint16_t synch_DCM; /**< Lower limit of the synchronous normal activation. [ADC_units] */
    uint16_t synch_ICP; /**< Lower limit of the synchronous DCM activation. [ADC_units] */
    uint16_t bridge_A_B_il_factor; /**< Factor of the dead time shrinking with the input current. [integer] */
    uint16_t bridge_il_ratio; /**< Ratio of the dead time shrinking with the input current. [Power of 2] */
    uint16_t debug_fan; /**< Debugging. Deactivation of fan protection. [Bool] */
    uint16_t debug_soft; /**< Debugging. Deactivation of input voltage control. [Bool] */
    uint16_t debug_vin; /**< Debugging. Deactivation of soft start protection. [Bool] */
    uint16_t min_phase; /**< Minimum allowed phase shift. [CCU_clock] */
    uint16_t burst_stop_limit; /**< Under this shift the PWM is trapped. [CCU_clock] */
    uint16_t burst_low_limit; /**< Under this shift the burst mode starts. [CCU_clock] */
    uint16_t burst_high_limit; /**< Over this shift the busrt mode stops. [CCU_clock] */
    uint16_t burst_phase; /**< Minimum shift during burst mode. [CCU_clock] */
    uint16_t burst_trap_cyc; /**< Number of skipped cycles between bursts. [control_cyc] */
    uint16_t burst_lenght; /**< Number of pulses of a burst. [rising_edge] */
    uint16_t vin_min_high; /**< Minimum input voltage, upper threshold. Around 350V. [ADC_units] */
    uint16_t master_key; /**< Key used to store the first upload of the software a set of default parameters. */
    uint16_t bridge_C_D_il_factor; /**< Factor of the dead time shrinking with the input current. [integer] */
    uint16_t synch_ON_DCM_dly; /**< Delay before rising edge of synchronous rectifiers in DCM. [CCU_clock] */
    uint16_t synch_OFF_DCM_dly; /**< Delay before falling edge of synchronous rectifiers in DCM. [CCU_clock] */
    uint16_t boost_dead_time_A_B; /**< Dead time for bridge signals A B in Boost mode. [CCU_clock] */
    uint16_t boost_dead_time_C_D; /**< Dead time for bridge signals C D in Boost mode. [CCU_clock] */
} params_t;

/*---------------------------------------------------------------------------*/
extern uint32_t XMC_USIC_CH_TXFIFO_GetLevel(XMC_USIC_CH_t *const channel);
extern const params_t *parameters_ROM;
extern params_t parameters_RAM;
extern params_t parameters_DFLT;
void uart_transmit();
void uart_receive();
void load_ROM_parameters();
void check_RAM_parameters();

#endif /* __COMMUNICATION_H_ */
/** @} */
